package com.learn;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.learn.pojo.Item;
import com.learn.repository.ItemDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 简单的增删改查
 */
@SpringBootTest(classes = {EsSpringApplication.class})
@RunWith(SpringRunner.class)
public class EsTest01 {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private ItemDao itemdao;


    //============================== 不使用Repository    开始  ================================
    //创建索引并增加映射配置
    @Test   //import org.junit.Test;
    public void createIndex() {
        //创建索引，系统初始化会自动创建索引
        IndexOperations ops = restTemplate.indexOps(Item.class);
        //创建索引
        // ops.create();

        //创建映射
        Document mapping = ops.createMapping();
        ops.putMapping(mapping);

        System.out.println("创建索引");
    }

    /**
     * 删除索引
     */
    @Test
    public void delete() {
        IndexOperations indexOperations = restTemplate.indexOps(Item.class);
        indexOperations.delete();
    }

    /**
     * 新增文档
     */
    @Test
    public void createDocument() {
        Item item = new Item();
        item.setId("10010");
        item.setPrice(110l);
        item.setSellPoint("中国联通");
        item.setNum(20);
        item.setTitle("中国联通");
        item.setItemDesc("中国联通");

        IndexQuery query = new IndexQueryBuilder()
                //添加对象
                .withObject(item)
                .build();
        //IndexCoordinates.of("索引名称")
        String primaryKey = restTemplate.index(query, IndexCoordinates.of("ego_item"));
    }

    /**
     * 修改文档
     * 局部更新文档
     */
    @Test
    public void updateDocument() throws JsonProcessingException {
        //将id为10010的name改为中国联通
        Document document = Document.create();
        document.put("name", "中国联通");
        UpdateQuery updateQuery = UpdateQuery
                .builder("10010")
                .withDocument(document)
                .build();
        restTemplate.update(updateQuery, IndexCoordinates.of("ego_item"));
    }

    /**
     * 删除
     */
    @Test
    public void deleteDocument() {
        String id = restTemplate.delete("10010", IndexCoordinates.of("ego_item"));
        System.out.println(id);
    }

    /**
     * 查全部
     */
    @Test
    public void queryDocument() {
        Query query = Query.findAll();
        SearchHits<Item> hits = restTemplate.search(query, Item.class, IndexCoordinates.of("ego_item"));
        hits.getSearchHits().forEach(System.out::println);
    }

    /**
     * 查全部
     */
//    @Test
//    public void queryMustDocument() {
//        List<? extends Query> query = new ArrayList<>();
//        query.add(BoostingQueryBuilder.parseInnerQueryBuilder());
//        restTemplate.multiSearch(query, Item.class, IndexCoordinates.of("ego_item"));
//
//    }

    //============================== 不使用Repository    结束  ================================


    //============================== 使用Repository     开始  ================================
    @Test
    public void repositoryCreateDocument() {
        for (int i=11;i<=20;i++){
            Item item = new Item();
            item.setId(String.valueOf(i));
            item.setPrice(2l*i);
            item.setSellPoint(UUID.randomUUID().toString());
            item.setNum(5*i);
            item.setTitle("中国联通:"+i);
            item.setItemDesc(i+"联通 三大运营商之一");
            Item save = itemdao.save(item);
        }

    }

    //修改
    @Test
    public void update() {
        Item item = new Item();
        item.setId("10010");
        item.setPrice(10010l);
        item.setSellPoint("联通xxx");
        item.setNum(10);
        item.setTitle("中国联通xxx");
        item.setItemDesc("联通xxx 三大运营商之一");
        Item save = itemdao.save(item);
    }

    //根据 id 查询
    @Test
    public void findById() {
        Item item = itemdao.findById(10010l).get();
        System.out.println(item);
    }
    //查询所有
    @Test
    public void findAll(){
        Iterable<Item> all = itemdao.findAll();
        for (Item product : all) {
            System.out.println(product);
        }
    }

    //删除
    @Test
    public void delete2(){
        Item product = new Item();
        product.setId("10010");
        itemdao.delete(product);
    }

    //批量新增
    @Test
    public void saveAll(){
        List<Item> productList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Item item = new Item();
            item.setId(String.valueOf(i));
            item.setPrice(Long.valueOf(i));
            item.setSellPoint("SellPointxxx:"+i);
            item.setNum(10+5*i);
            item.setTitle("中国xxx:"+i);
            item.setItemDesc("desc"+i);
            productList.add(item);
        }
        itemdao.saveAll(productList);
    }

    //分页查询
    @Test
    public void findByPageable(){
        //设置排序(排序方式，正序还是倒序，排序的 id)
        Sort sort = Sort.by(Sort.Direction.DESC,"price");
        int currentPage=0;//当前页，第一页从 0 开始，1 表示第二页
        int pageSize = 5;//每页显示多少条
        //设置查询分页
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);

        //分页查询
        Page<Item> productPage = itemdao.findAll(pageRequest);
        for (Item Product : productPage.getContent()) {
            System.out.println(Product);
        }
    }
    //============================== 使用Repository     结束  ================================

}
